package com.br3akr.rollerClient.client;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.Observable;

import com.br3akr.rollerTransferProtocol.transferProtocol.FromClient;
import com.br3akr.rollerTransferProtocol.transferProtocol.PlayerEntry;
import com.br3akr.rollerTransferProtocol.transferProtocol.PlayerState;

public class Client extends Observable {

	ClientThread ct;
	ObjectOutputStream out;
	String message;
	PlayerState state;
	PlayerEntry[] players;
	
	public Client() {
		try {
			ct = new ClientThread(this);
			ct.start();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void sendAction(FromClient output) {
		if (out != null) {
			try {
				out.writeObject(output);
			} catch (IOException e) {
				e.printStackTrace();
				updatePlayer("Unable to write to server.", null, null);
			}
		}
	}
	
	public boolean isConnected() {
		return out != null;
	}
	
	public void setOut(ObjectOutputStream out) {
		this.out = out;
	}
	
	public String getMessage() {
		return message;
	}
	
	public PlayerState getState() {
		return state;
	}
	
	public PlayerEntry[] getPlayers() {
		return players;
	}
	
	/**
	 * Sets the client's data, and notifies any applications observing the client. If the state, or players
	 * are null, it is assumed they are still the same.
	 * @param message The message to display from the server.
	 * @param state The current state of the player's character.
	 * @param players An array of PlayerEntry's to update the player with known information about other players 
	 */
	public void updatePlayer(String message, PlayerState state, PlayerEntry[] players) {
		this.message = message;
		if (state != null) {
			this.state = state;
		}
		if (players != null) {
			this.players = players;
		}
		setChanged();
		notifyObservers();
	}
}